package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.response.ArrivalRate;
import com.xmy.cultivate.entity.response.OrderDetailRs;
import com.xmy.cultivate.entity.views.EnrollList;
import com.xmy.cultivate.entity.views.FirstSignUp;
import com.xmy.cultivate.entity.views.IncomeDayReport;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.CourseMapper;
import com.xmy.cultivate.mapper.GradeMapper;
import com.xmy.cultivate.mapper.OrderDetailMapper;
import com.xmy.cultivate.mapper.StaffMapper;
import com.xmy.cultivate.service.IOrderDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.service.IQuarterService;
import com.xmy.cultivate.service.IStudentTypeService;
import com.xmy.cultivate.util.ConfigData;
import com.xmy.cultivate.util.ResultCode;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单报名信息 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-08-01
 */
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail> implements IOrderDetailService {

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    CourseMapper courseMapper;

    @Autowired
    GradeMapper gradeMapper;

    @Autowired
    StaffMapper staffMapper;

    @Autowired
    IStudentTypeService iStudentTypeService;

    @Autowired
    IQuarterService iQuarterService;

    public IPage<EnrollList> getEnrollList(IPage<?> page, Wrapper wrapper) {
        IPage<EnrollList> enrollListIPage = orderDetailMapper.getEnrollList(page, wrapper);
        for (EnrollList enrollList : enrollListIPage.getRecords()) {
            Course course = courseMapper.selectById(enrollList.getCourseId());
            if (course != null) {
                enrollList.setSubjectsId(course.getSubjectsId());
                //System.out.print("---"+enrollList.getSchoolId()+"="+enrollList.getStudentId()+"="+course.getId());
                boolean isNew = iStudentTypeService.isNew(enrollList.getSchoolId(), enrollList.getStudentId(), course.getSubjectsId());
                if (isNew) {
                    enrollList.setIsNewStudent(1);
                } else {
                    enrollList.setIsNewStudent(2);
                }
            }
        }

        return enrollListIPage;
    }

    public Map<String, BigDecimal> enrollListMoney(Wrapper wrapper) {
        BigDecimal solidPrice = orderDetailMapper.getSolidPrice(wrapper);
        BigDecimal studentCount = orderDetailMapper.getAllStudentCount(wrapper);

        Map<String, BigDecimal> map = new HashMap<>();
        map.put("solidPrice", solidPrice);
        map.put("studentCount", studentCount);
        return map;
    }


    public List<OrderDetail> orderDetail(Wrapper wrapper) {
        return orderDetailMapper.orderDetail(wrapper);
    }

    public Integer getApplyCountForSubjects(Long schoolId, Long studentId, Long subjectsId, Integer newYeartPart, Integer newNum) {
        return orderDetailMapper.getApplyCountForSubjects(schoolId, studentId, subjectsId, newYeartPart, newNum);
    }

    public OrderDetail getLastOneForStudent(Long schoolId, Long studentId, Long subjectsId) {
        return orderDetailMapper.getLastOneForSubjectId(schoolId, studentId, subjectsId);
    }

    /**
     * 办理中心获取学员报读信息
     *
     * @return
     */
    public List<OrderDetail> GetLessonByStuInfoId(Wrapper wrapper) {
        return orderDetailMapper.GetLessonByStuInfoId(wrapper);
    }

    public List<OrderDetail> getLessonByCourseId(Long courseId, Long studentId, Long schoolId) {
        return orderDetailMapper.getLessonByCourseId(courseId, studentId, schoolId);
    }

    public List<Organization> getSignUpSchoolListForWhere(@Param(Constants.WRAPPER) Wrapper wrapper) {
        return orderDetailMapper.getSignUpSchoolListForWhere(wrapper);
    }

    public FirstSignUp getFirstSignUp(Long studentId, Long gradeId, Integer count) {
        return orderDetailMapper.getFirstSignUp(studentId, gradeId, count);
    }

    public Boolean stopCourse(Long orderDetailId) {

        OrderDetail orderDetail = orderDetailMapper.selectById(orderDetailId);
        if (orderDetail == null) {
            throw new CommonException(ResultCode.ORDERDETAIL_NOT);
        }

        if (orderDetail.getReadingStatus() != ReadingStatusEnum.IN_READING) {
            throw new CommonException(ResultCode.STATUSNOT);
        }
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("order_id", orderDetail.getOrderId()).ne("status", 2);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailQueryWrapper);


        for (OrderDetail orderDetailTemp : orderDetailList) {

        }
        return true;
    }

    public IPage<IncomeDayReport> getIncomeDayReport(IPage<?> page, Wrapper wrapper) {
        IPage<IncomeDayReport> iPage = orderDetailMapper.getIncomeDayReport(page, wrapper);
        for (IncomeDayReport incomeDayReport : iPage.getRecords()) {
            if (incomeDayReport.getGradeId() != null) {
                Grade grade = gradeMapper.selectById(incomeDayReport.getGradeId());
                Course course = courseMapper.selectById(incomeDayReport.getCourseId());
                if (grade != null) {
                    incomeDayReport.setGradeName(grade.getName());
                    Staff staff = staffMapper.selectById(grade.getTeacherId());
                    if (staff != null) {
                        incomeDayReport.setTeacherName(staff.getName());
                    }
                }
                if (course != null) {
                    incomeDayReport.setSubjectsName(ConfigData.getSubjectsNameForNum(Integer.parseInt(course.getSubjectsId().toString())));
                }
            }
            Course course = courseMapper.selectById(incomeDayReport.getCourseId());
            incomeDayReport.setYearClassName(ConfigData.getYearClassForNum(course.getYearClassId().getKey()));
        }

        return iPage;
    }

    @Override
    public List<ArrivalRate> getLosseRade(String yearPart, String quarterNum, String schoolId, String subjectsId, String startDate, String endDate, String type, String lessonType, String yearClassStr) {

        Quarter quarterNow = iQuarterService.getNowQuarter();
        //是否查看历史的，1是，0否
        Integer isHistory = 0;
        if (!String.valueOf(quarterNow.getYearPart()).equals(yearPart) || !String.valueOf(quarterNow.getNum()).equals(quarterNum)) {
            isHistory = 1;
        }

        Integer payYearPart = Integer.parseInt(yearPart);
        Integer payQuarterNum = Integer.parseInt(quarterNum);

        Integer searchYearAndQuarter = Integer.parseInt(yearPart + "" + quarterNum);
        Integer nextYearAndQuarter = 0;
        if (isHistory.equals(1) && LocalDate.parse(startDate).equals(LocalDate.now())) {
            Integer quarterId = iQuarterService.getIdForYearPartAndNum(Integer.parseInt(yearPart), Integer.parseInt(quarterNum));
            Quarter nextQuater = iQuarterService.getQuarterMaxForId(quarterId + 2);//获取当前学期的两个学期后的学期
            if (nextQuater != null) {
                nextYearAndQuarter = Integer.parseInt(nextQuater.getYearPart() + "" + nextQuater.getNum());
            }
            payYearPart = quarterNow.getYearPart();
            payQuarterNum = quarterNow.getNum();
        }
        return orderDetailMapper.getLosseRade(yearPart, quarterNum, schoolId, subjectsId, startDate, endDate, type, lessonType, isHistory, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassStr);
    }

    @Override
    public List<ArrivalRate> getLosseRadeDetail(String yearPart, String quarterNum, String schoolId, String teacherId, String gradeId, String subjectsId, String startDate, String endDate, String type, String lessonType, String yearClassStr) {

        Quarter quarterNow = iQuarterService.getNowQuarter();
        //是否查看历史的，1是，0否
        Integer isHistory = 0;
        if (!String.valueOf(quarterNow.getYearPart()).equals(yearPart) || !String.valueOf(quarterNow.getNum()).equals(quarterNum)) {
            isHistory = 1;
        }
        Integer payYearPart = Integer.parseInt(yearPart);
        Integer payQuarterNum = Integer.parseInt(quarterNum);

        Integer searchYearAndQuarter = Integer.parseInt(yearPart + "" + quarterNum);
        Integer nextYearAndQuarter = 0;
        if (isHistory.equals(1) && LocalDate.parse(startDate).equals(LocalDate.now())) {
            Integer quarterId = iQuarterService.getIdForYearPartAndNum(Integer.parseInt(yearPart), Integer.parseInt(quarterNum));
            Quarter nextQuater = iQuarterService.getQuarterMaxForId(quarterId + 2);//获取当前学期的两个学期后的学期
            if (nextQuater != null) {
                nextYearAndQuarter = Integer.parseInt(nextQuater.getYearPart() + "" + nextQuater.getNum());
            }
            payYearPart = quarterNow.getYearPart();
            payQuarterNum = quarterNow.getNum();
        }
        return orderDetailMapper.getLosseRadeDetail(yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, startDate, endDate, type, lessonType, isHistory, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassStr);
    }

    /**
     * 获取报读课程
     *
     * @param wrapper
     * @return
     */
    public OrderDetail getApplyCourse(Wrapper wrapper) {
        return orderDetailMapper.getApplyCourse(wrapper);
    }

    @Override
    public OrderDetail getSumResidueCourseHouse(Long courseId, Long studentId, Long schoolId) {
        return orderDetailMapper.getSumResidueCourseHouse(courseId, studentId, schoolId);
    }

    @Override
    public Integer getResidueCourseCountForSubjects1(Long schoolId, Long studentId, Long subjectsId, Integer lessonType){
        return orderDetailMapper.getResidueCourseCountForSubjects1(schoolId,studentId,subjectsId,lessonType);
    }

    @Override
    public List<OrderDetail> getResidueOrderDetail(Long schoolId,
                                                   Long studentId,
                                                   Long subjectsId,
                                                   Integer lessonType
    ) {
        return orderDetailMapper.getResidueOrderDetail(schoolId,studentId,subjectsId,lessonType);
    }

    @Override
    public IPage<OrderDetailRs> getOrderDetailList(IPage<OrderDetailRs> page, Long createdId,String payType,String yearPart,String  quarterNum,String startDate,String endDate,String schoolId,String subjectsId,String studentName) {
        return orderDetailMapper.getOrderDetailList(page, createdId,payType,yearPart,quarterNum,startDate,endDate,schoolId, subjectsId,studentName);
    }
    @Override
    public OrderDetailRs orderDetailForId(Long id){
        return orderDetailMapper.orderDetailForId(id);
    }
}
